package com.itcast.netty.handler.adapter;

import com.itcast.common.constants.CommonConstants;
import com.itcast.common.entity.MethodInvokeMeta;
import com.itcast.netty.constants.NettyConstants;
import com.itcast.netty.handler.dispatcher.RequestDispatcher;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 通道适配器
 *
 * @author zheng.zhang
 */
@Slf4j
@Component
public class ServerChannelHandlerAdapter extends ChannelHandlerAdapter {
    /**
     * 注入请求分排器
     */
    @Autowired
    private RequestDispatcher dispatcher;

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        MethodInvokeMeta invokeMeta = (MethodInvokeMeta) msg;
        // 过滤toString方法
        if (invokeMeta.getMethodName().endsWith(CommonConstants.TO_STRING) && !CommonConstants.STRING_TYPE.equals(invokeMeta.getReturnType().toString())) {
            log.info("客户端传入参数:{}, 返回值: {}", invokeMeta.getArgs(), invokeMeta.getReturnType());
            dispatcher.dispatcher(ctx, invokeMeta);
        }
    }
}
